#include "TextureManager.h"
#include "../../Renderer/D3D9Renderer.h"
#include "../Misc/DebugOutput.h"

map<string, IDirect3DTexture9*> TextureManager::textureMap;

bool TextureManager::LoadTexture(string _filePath, IDirect3DTexture9*& _texture)
{
	map<string, IDirect3DTexture9*>::iterator ite;

	ite = textureMap.find(_filePath);
	
	if(ite == textureMap.end())
	{
		HRESULT result = D3DXCreateTextureFromFile(D3D9Renderer::device, _filePath.c_str(), &_texture);

		if(result != D3D_OK)
		{
#ifdef _DEBUG
			stringstream error;
			error	<< "TEXTURE FROM FILE: " << _filePath;
			DebugOutput::Print(DebugOutput::RENDER_MSG, DebugOutput::FAILURE_CREATE, error.str().c_str());
#endif
			return false;
		}

		#ifdef _DEBUG
			stringstream success;
			success	<< "TEXTURE FROM FILE: " << _filePath;
			DebugOutput::Print(DebugOutput::RENDER_MSG, DebugOutput::SUCCESS_CREATE, success.str().c_str());
		#endif
		
		textureMap.insert(map<string, IDirect3DTexture9*>::value_type(_filePath, _texture));
	}
	else
	{
		_texture = ite->second;
	}

	return true;
}

bool TextureManager::CreateTexture(UINT _width, UINT _height, UINT _levels, DWORD _usage, D3DFORMAT _format, D3DPOOL _pool, IDirect3DTexture9*& _texture, HANDLE _sharedHandle)
{
	HRESULT result = D3D9Renderer::device->CreateTexture(_width, _height, _levels, D3DUSAGE_RENDERTARGET, _format, D3DPOOL_DEFAULT, &_texture, 0);
	
	if(result != D3D_OK)
	{
		DebugOutput::Print(DebugOutput::RENDER_MSG, DebugOutput::FAILURE_CREATE, "TEXTURE CREATE");
		return false;
	}

	return true;
}

void TextureManager::ClearTextureCache()
{
	map<string, IDirect3DTexture9*>::iterator ite = textureMap.begin();

	while(ite != textureMap.end())
	{
		ite->second->Release();
		textureMap.erase(ite);
		ite = textureMap.begin();
	}
}